<template>
  <div class="customer-service-page">
    <!-- 页面顶部标题 -->
    <div class="header">
      <img src="https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/826.jpg?x-oss-process=image/format,webp" alt="客服头像" class="header-image" />
    </div>

    <!-- 聊天区域 -->
    <div class="chat-container">
      <div class="chat-messages" ref="chatMessages">
        <!-- 消息列表 -->
        <div v-for="(message, index) in messages" :key="index" class="message-item" :class="{ 'user-message': message.sender === 'user' }">
          <div class="message-bubble" :class="{ 'user-bubble': message.sender === 'user' }">
            <!-- 客服消息 -->
            <template v-if="message.sender === 'service'">
              <div class="avatar">
                <img src="https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/logo.jpg?x-oss-process=image/format,webp" alt="客服" />
              </div>
              <div class="message-content">
                <div v-if="message.type === 'text'" class="text-message">
                  {{ message.content }}
                </div>
                <div v-else-if="message.type === 'image'" class="image-message">
                  <img :src="message.content" alt="推荐图片" />
                </div>
                <div v-else-if="message.type === 'api-image'" class="api-image-container">
                  <img 
                    :src="message.content" 
                    alt="推荐照片" 
                    class="api-image"
                    @touchstart="handleTouchStart"
                    @touchend="handleTouchEnd"
                    @click="handleImageClick(message)"
                    @contextmenu.prevent
                  />
<!--                  <div v-if="isIOSDevice" class="save-tip">长按图片保存到相册</div>-->
<!--                  <div v-if="!isIOSDevice" class="save-tip">点击图片添加</div>-->
                  <div  class="save-tip">点击图片添加</div>
                </div>
              </div>
            </template>
            
            <!-- 用户消息 -->
            <template v-else>
              <div class="message-content user-content">
                <div class="text-message user-text">
                  {{ message.content }}
                </div>
              </div>
              <div class="avatar user-avatar">
                 <img src="/images/824.jpg" alt="用户" />
               </div>
            </template>
          </div>
          <!-- 时间单独一行显示，只显示客服消息的时间 -->
          <div v-if="message.sender === 'service'" class="message-time-row">
            {{ formatTime(message.timestamp) }}
          </div>
        </div>
        

      </div>
    </div>
    
    <!-- 底部按钮 -->
    <div v-if="showBottomButtons" class="bottom-buttons">
      <button @click="handleButtonClick('need')" class="action-btn need-btn">
        需要
      </button>
      <button @click="handleButtonClick('no-need')" class="action-btn no-need-btn">
        不需要
      </button>
    </div>
    
    <!-- 新增的底部样式 -->
    <div v-if="showBottomToolbar" class="bottom-toolbar">
      <div class="toolbar-content">
        <div class="toolbar-icon">
              <img src="https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/IMG_1875.PNG?x-oss-process=image/format,webp" alt="voice" width="180" height="180" />
            </div>
        <div class="input-container">
          <form @submit.prevent="sendMessage">
                <input type="text" placeholder="发送消息" class="message-input" v-model="message" @focus="showSendButton = true" @blur="handleInputBlur" />
              </form>
          <div class="input-icons" v-if="!showSendButton">
            <div class="toolbar-icon" >
              <img src="https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/IMG_1877.PNG?x-oss-process=image/format,webp" alt="voice" width="180" height="180" />
            </div>
            <div class="toolbar-icon" >
              <img src="https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/IMG_1878.PNG?x-oss-process=image/format,webp" alt="emoji" width="180" height="180" />
            </div>
            <div class="toolbar-icon" >
              <img src="https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/IMG_1879.PNG?x-oss-process=image/format,webp" alt="add" width="180" height="180"/>
            </div>
          </div>
          <div class="input-icons" v-if="showSendButton">
            <div >
              <button type="button" class="send-button" @mousedown="sendMessage" >发送</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    

  </div>
</template>

<script>
export default {
  name: 'CustomerService',
  data() {
    return {
      message: '',
      showSendButton: false,
      messages: [],
      showBottomButtons: true,
      showBottomToolbar: true,
      fixedImageUrl: 'https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/pic/images/sayHello.jpg?x-oss-process=image/format,webp',
      showLoading: false, // 加载状态
      // 消息模板
      messageTemplates: {
        welcome: '小哥哥，是考虑认真处对象的话，推两个妹子给你呀~她们的照片和情况可以给你看看，试试你们俩能不能看对眼儿~',
        qrCodePrompt: '可以复制保存下我发你VX二维码，VX扫码添加下，推两个女生给你，她们的照片和情况发给你看看试试你俩能不能看对眼儿',
        errorMessage: '抱歉，服务暂时不可用，请稍后再试'
      },
      // 延迟时间常量
      delays: {
        welcomeMessage: 800,
        imageMessage: 800,
        qrCodeMessage: 500
      },
      // API配置
      apiConfig: {
        recommendService: 'https://api.yesido1314.cn/h5/page/recommendService',
        clickService: 'https://api.yesido1314.cn/h5/qrcode/touch',
        defaultImage: 'https://loanclient.oss-cn-hangzhou.aliyuncs.com/yesido/pictures/images/yaoyao.jpg'
      },
      // 自动点击相关
      autoClickTimer: null, // 自动点击定时器
      userHasClicked: false, // 用户是否已点击按钮
      // URL参数
      clickId: '', // 从URL获取的clickid参数
      // 长按相关
      longPressTimer: null, // 长按定时器
      isLongPress: false, // 是否触发了长按

    }
  },
  computed: {
    hasMessages() {
      return this.messages.length > 0
    },
    lastMessage() {
      return this.messages[this.messages.length - 1]
    },
    isIOSDevice() {
      console.log("navigator.userAgent",navigator.userAgent);
      return /iPad|iPhone|iPod/.test(navigator.userAgent)
    },
    getAgent(){
      return navigator.userAgent;
    }
  },
  mounted() {
    this.getClickIdFromUrl()
    this.startConversation()
    this.setupAutoClick()
  },
  beforeDestroy() {
    // 清除定时器，防止内存泄漏
    if (this.autoClickTimer) {
      clearTimeout(this.autoClickTimer)
      this.autoClickTimer = null
    }
    if (this.longPressTimer) {
      clearTimeout(this.longPressTimer)
      this.longPressTimer = null
    }
  },
  methods: {
    // 从URL获取clickid参数
    getClickIdFromUrl() {
      const urlParams = new URLSearchParams(window.location.search)
      this.clickId = urlParams.get('clickid') || ''
      console.log('获取clickid:', this.clickId)
    },
    
    startConversation() {
      // 发送欢迎消息
      setTimeout(() => {
        this.addMessage('text', this.messageTemplates.welcome)
        
        // 发送图片
        setTimeout(() => {
          this.addMessage('image', this.fixedImageUrl)
        }, this.delays.imageMessage)
      }, this.delays.welcomeMessage)
    },
    
    addMessage(type, content) {
      this.messages.push({
        type,
        content,
        timestamp: new Date(),
        sender: 'service' // 客服消息
      })
      
      // 滚动到底部
      this.scrollToBottom()
    },
    
    // 添加API图片消息，包含跳转URL
    addApiImageMessage(imageUrl, jumpUrl) {
      this.messages.push({
        type: 'api-image',
        content: imageUrl,
        jumpUrl: jumpUrl, // 保存跳转URL
        timestamp: new Date(),
        sender: 'service' // 客服消息
      })
      
      // 滚动到底部
      this.scrollToBottom()
    },
    
    addUserMessage(content) {
      this.messages.push({
        type: 'text',
        content,
        timestamp: new Date(),
        sender: 'user' // 用户消息
      })
      
      // 滚动到底部
      this.scrollToBottom()
    },
    
    async handleButtonClick(action) {
      // 标记用户已点击，清除自动点击定时器
      this.userHasClicked = true
      if (this.autoClickTimer) {
        clearTimeout(this.autoClickTimer)
        this.autoClickTimer = null
      }
      
      // 如果用户点击"需要"，先显示用户消息
      if (action === 'need') {
        this.addUserMessage('需要')
      }
      
      try {
        this.showLoading = true
        // 构建带有clickid参数的URL
        let apiUrl = this.apiConfig.recommendService
        if (this.clickId) {
          apiUrl += `?clickId=${encodeURIComponent(this.clickId)}`
        }
        
        const response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ action, type: 'userClick' ,agent: this.getAgent})
        })
        
        const result = await response.json()
        
        if (result.code === 0 && result.data) {
          this.handleApiSuccess(result.data)
        } else {
          console.error('API返回错误:', result)
          this.handleApiError(new Error('API返回错误'))
        }
      } catch (error) {
        console.error('请求失败:', error)
        this.handleApiError(error)
      } finally {
        this.showLoading = false
      }
    },
    
    handleApiSuccess(imageData) {
      // 等待500毫秒后执行后续逻辑
      setTimeout(() => {
        // 将API图片作为消息添加到消息列表，同时保存跳转URL
        this.addApiImageMessage(imageData.pictureUrl, imageData.jumpUrl)
        // 隐藏底部按钮和工具栏
        this.showBottomButtons = false
        this.showBottomToolbar = true
        
        // 延迟发送二维码提示消息
        setTimeout(() => {
          this.addMessage('text', this.messageTemplates.qrCodePrompt)
        }, this.delays.qrCodeMessage)
      }, 1500)
    },

    handleApiError(error) {
      console.error('API请求失败:', error)
      // 等待500毫秒后执行后续逻辑
      setTimeout(() => {
        // 将默认图片作为消息添加到消息列表，使用默认跳转URL
        const defaultJumpUrl = 'https://work.weixin.qq.com/ca/cawcde47437bd9892d'
        this.addApiImageMessage(this.apiConfig.defaultImage, defaultJumpUrl)
        // 隐藏底部按钮和工具栏
        this.showBottomButtons = false
        this.showBottomToolbar = true;
        
        // 延迟发送二维码提示消息
        setTimeout(() => {
          this.addMessage('text', this.messageTemplates.qrCodePrompt)
        }, this.delays.qrCodeMessage)
      }, 500)
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const chatMessages = this.$refs.chatMessages
        if (chatMessages) {
          chatMessages.scrollTop = chatMessages.scrollHeight
        }
      })
    },

    handleIconClick() {
      // 图标点击无响应
      return false
    },
    
    formatTime(timestamp) {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${hours}:${minutes}`
    },
    
    // 设置自动点击定时器
    setupAutoClick() {
      this.autoClickTimer = setTimeout(() => {
        // 6秒后如果用户未点击按钮，自动执行"需要"的逻辑
        if (!this.userHasClicked && this.showBottomButtons) {
          this.autoClickNeed()
        }
      }, 6000) // 6秒
    },
    
    // 自动点击"需要"按钮的逻辑（不显示用户消息）
     async autoClickNeed() {
       try {
         this.showLoading = true
         // 构建带有clickid参数的URL
         let apiUrl = this.apiConfig.recommendService
         if (this.clickId) {
           apiUrl += `?clickId=${encodeURIComponent(this.clickId)}`
         }
         
         const response = await fetch(apiUrl, {
           method: 'POST',
           headers: {
             'Content-Type': 'application/json'
           },
           body: JSON.stringify({ action: 'need', type: 'autoClick' ,agent: this.getAgent})
         })
        
        const result = await response.json()
        
        if (result.code === 0 && result.data) {
          this.handleApiSuccess(result.data)
        } else {
          console.error('API返回错误:', result)
          this.handleApiError(new Error('API返回错误'))
        }
      } catch (error) {
        console.error('自动点击请求失败:', error)
        this.handleApiError(error)
      } finally {
         this.showLoading = false
       }
     },
     
     // 处理触摸开始事件
      handleTouchStart() {
        this.isLongPress = false
        // 设置长按定时器（通常500ms认为是长按）
        this.longPressTimer = setTimeout(() => {
          this.isLongPress = true
          this.handleLongPress()
        }, 500)
      },
      
      // 处理触摸结束事件
      handleTouchEnd() {
        // 清除长按定时器
        if (this.longPressTimer) {
          clearTimeout(this.longPressTimer)
          this.longPressTimer = null
        }
      },
      
      // 处理长按事件
      async handleLongPress() {
        try {
          // 构建API URL
          // let apiUrl = 'https://api.yesido1314.cn/h5/qrcode/keepTouch'
          let apiUrl = 'https://api.yesido1314.cn/h5/qrcode/keepTouch'
          if (this.clickId) {
            apiUrl += `?clickId=${encodeURIComponent(this.clickId)}`
          }
          
          // 发送POST请求，忽略响应
          fetch(apiUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
             body: JSON.stringify({ type: 'userClick' ,agent: this.getAgent})
          }).catch(() => {
            // 忽略错误，不做任何处理
            console.log('长按请求发送:', apiUrl)
          })
          
          console.log('二维码长按事件触发，请求已发送:', apiUrl)
        } catch {
          // 忽略所有错误
          console.log('长按请求异常，已忽略')
        }
      },
      
      // 发送消息方法
      sendMessage() {
        console.log("sendMessage");
        // 检查输入框是否有内容
        if (this.message && this.message.trim()) {
          // 添加用户消息到聊天记录
          this.addUserMessage(this.message.trim())
          
          // 清空输入框
          this.message = ''
          
          // 隐藏发送按钮，显示输入图标
          this.showSendButton = false
          this.handleButtonClick('');
        }
      },
      
      // 处理输入框失去焦点事件
      handleInputBlur() {
        // 延迟隐藏发送按钮，给点击事件时间执行
        setTimeout(() => {
          this.showSendButton = false
        }, 150)
      },

      
      // 下载图片（非iOS设备）
      downloadImage(imageUrl) {
        try {
          // 创建一个临时的a标签来下载图片
          const link = document.createElement('a')
          link.href = imageUrl
          link.download = `image_${Date.now()}.jpg`
          link.target = '_blank'
          
          // 添加到DOM并触发点击
          document.body.appendChild(link)
          link.click()
          
          // 清理DOM
          setTimeout(() => {
            document.body.removeChild(link)
          }, 100)
          
          console.log('图片下载已触发')
        } catch (error) {
          console.log('图片下载失败:', error)
          // 如果下载失败，尝试在新窗口打开图片
          try {
            window.open(imageUrl, '_blank')
          } catch (e) {
            console.log('打开图片失败:', e)
            alert('无法保存图片，请手动保存')
          }
        }
      },
      
      // 处理图片点击事件
      async handleImageClick(message) {
        console.log("handleImageClick", message);
        let apiUrl = this.apiConfig.clickService
        if (this.clickId) {
          apiUrl += `?clickId=${encodeURIComponent(this.clickId)}`
        }
        
        await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ type: 'userClick' ,agent: this.getAgent})
        })
        
        
        
        // if(this.isIOSDevice){
        //   return ;
        // }
        // 如果消息有跳转URL，则跳转到该URL
        if (message.jumpUrl) {
          try {
            console.log("window.open before",message.jumpUrl)
            // iOS设备需要在用户交互事件中立即调用window.open
            if (this.isIOSDevice) {
              // 对于iOS设备，直接使用location.href进行跳转
              window.location.href = message.jumpUrl
            } else {
              // 非iOS设备使用window.open
              window.open(message.jumpUrl, '_blank')
            }
            console.log('跳转到URL:', message.jumpUrl)
          } catch (error) {
            console.log('跳转失败:', error)
            alert('无法打开链接')
          }
        }
      }
  }
}
</script>

<style scoped>
.customer-service-page {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

.header {
  width: 100%;
  text-align: center;
  position: sticky;
  padding-bottom: 5px;
  top: 0;
  z-index: 100;
  border-bottom: 1px solid #cccccc;
}

.header-image {
  width: 100%;
  height: 60px;
  object-fit: cover;
  display: block;
}

.chat-container {
  flex: 1;
  overflow: hidden;
  padding: 0px 0px;
  padding-bottom: 100px; /* 为底部按钮留出空间，确保至少20px间距 */
}

.chat-messages {
  height: 100%;
  overflow-y: auto;
  padding-right: 0px;
  padding-bottom: 20px; /* 确保最后一条消息与底部按钮保持20px间距 */
}

.message-item {
  margin-bottom: 20px;
}

.message-bubble {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.send-button{
  background-color: #1289ff;
  font-size: 16px;
  padding: 5px;
  border: 0px;
  border-radius: 15px;
  width:80px;
  color: white;
}

/* 用户消息样式 */
.user-message {
  display: flex;
  justify-content: flex-end;
}

.user-bubble {
  justify-content: flex-end;
}

.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  flex-shrink: 0;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 20px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-content {
  flex: 1;
  display: flex;
  max-width: 70%;
}

.text-message {
  background: #f3f3f5;
  padding: 12px 16px;
  border-radius: 18px;
  border-top-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 14px;
  line-height: 1.4;
  color: #333;
  text-align: left;
}

/* 用户消息内容样式 */
.user-content {
  max-width: 70%;
  display: flex;
  justify-content: flex-end;
  flex: none;
  margin-left: auto;
}

.user-text {
  background: #1289ff;
  color: white;
  border-top-left-radius: 18px;
  border-top-right-radius: 4px;
  border-bottom-left-radius: 18px;
  border-bottom-right-radius: 18px;
  text-align: right;
}

.user-avatar {
  background: #e3f2fd;
}

/* 消息时间行样式 */
.message-time-row {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin: 10px 0;
  line-height: 1;
  width: 100%;
}

.image-message {
  margin-top: 8px;
}

.image-message img {
  max-width: 100%;
  width: 140px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.api-image-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.api-image {
  max-width: 200px;
  height: auto;
  object-fit: cover;
  border-radius: 8px;
  flex-shrink: 0;
}

.save-tip {
  color: #999;
  font-size: 12px;
  margin-top: 5px;
  text-align: center;
  width: 100%;
}

/* 底部工具栏样式 */
.bottom-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  padding-top: 0px;
  padding-left: 5px;
  padding-right: 5px;
  padding-bottom: 10px;
  z-index: 999;
}

.toolbar-content {
  display: flex;
  align-items: center;
  gap: 12px;
  max-width: 100%;
  padding-bottom: 20px;
}

.toolbar-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 50%;
  cursor: pointer;
  transition: background-color 0.3s ease;
  flex-shrink: 0;
}

.toolbar-icon:hover {
  background: #e0e0e0;
}

.input-container {
  flex: 1;
  display: flex;
  margin-left: -10px;
  margin-right: 10px;;
  align-items: center;
  background: #f9f9f9;
  border: 1px solid #ddd;
  justify-content:space-between;
  border-radius: 20px;
  padding: 0 15px;
  gap: 8px;
}

.message-input {
  flex: 1;
  height: 40px;
  border: none;
  background: transparent;
  padding: 0;
  font-size: 14px;
  outline: none;
  color: #333;
}

.message-input::placeholder {
  color: #999;
}

.input-icons {
  display: flex;
  gap: 4px;
  justify-content: flex-end;
  margin-right: -5px;
}

.input-icons .toolbar-icon {
  width: 32px;
  height: 32px;
  background: transparent;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.input-icons .toolbar-icon:hover {
  background: #e0e0e0;
}

.message-input:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.save-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 107, 0.4);
}

.save-btn:active {
  transform: translateY(0);
}

.bottom-buttons {
  position: fixed;
  bottom: 85px;
  left: 0;
  right: 0;
  display: flex;
  gap: 10px;
  padding: 0 15px;
  background: #ffffff;
  z-index: 1000;
}

.action-btn {
  flex: 1;
  padding: 18px;
  border: none;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 20px;
  background: #1289ff;
  color: white;
}

.need-btn {
  background: #1289ff;
  color: white;
}

.need-btn:hover {
  background: #0d7ae6;
}

.no-need-btn {
  background: #1289ff;
  color: white;
}

.no-need-btn:hover {
  background: #0d7ae6;
}

.action-btn:active {
  transform: scale(0.98);
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 4px;
}

.chat-messages::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}



/* 响应式设计 */
@media (max-width: 480px) {
  .chat-container {
    padding-top: 20px;
  }
  
  .api-image-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .api-image {
    max-width: 180px;
    height: auto;
  }
  
  .action-btn {
    padding: 16px;
    font-size: 16px;
  }
}
</style>